package com.mocha.nezha.socket.handler;

import cn.hutool.core.util.StrUtil;
import com.mocha.common.core.MochaException;
import com.mocha.nezha.dmo.PCSwitchCameraMessage;
import com.mocha.nezha.nezha.NezhaClient;
import com.mocha.nezha.nezha.NezhaSessionManager;
import com.mocha.websocket.MochaWebSocketExecutor;
import com.mocha.websocket.command.MochaTextCommand;
import com.mocha.websocket.handler.MochaHandler;
import com.mocha.websocket.handler.MochaSocketTextHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * 前端 切换 摄像头信息
 * @author: songkui
 * @since: 2024/3/21 0:14
 */
@MochaHandler("CommandType.PcSwitchCamera")
@Service
@Slf4j
public class ClientSwitchCameraHandler implements MochaSocketTextHandler<PCSwitchCameraMessage> {


    @Override
    public void handle(MochaTextCommand<PCSwitchCameraMessage> command) throws MochaException {
        PCSwitchCameraMessage message = command.getRequest();
        if (null == message || StrUtil.isEmpty(message.getCameraCodes())){
            log.error("Pc Switch Camera: message is null; [sessionId: {}] ", command.getClient().getSessionId());
            return;
        }

        NezhaClient nezhaClient = NezhaSessionManager.getInstance().getNezhaClient(command.getSessionId());
        if (null == nezhaClient){
            log.error("Pc Switch Camera:  Login failure [sessionId: {}] ", command.getClient().getSessionId());
            command.getClient().disconnect();
            return;
        }
        log.info("Pc Switch Camera:[sid: {}, uid: {}, old camera: {}, new camera: {}] ", nezhaClient.getSessionId(), nezhaClient.getUserId(), nezhaClient.isAllCamera() ? "ALL" :  null != nezhaClient.getCameras() ? String.join(",", nezhaClient.getCameras()) : "null",  message.getCameraCodes());
        Executor executor = MochaWebSocketExecutor.getInstance().getDisruptor(nezhaClient.getParkCode().hashCode());
        executor = null == executor ? MochaWebSocketExecutor.getInstance().getDefaultExecutor() : executor;
        executor.execute(() ->{
            if ("ALL".equals(message.getCameraCodes())){
                NezhaSessionManager.getInstance().switchCamera(nezhaClient, null, true);
                nezhaClient.setAllCamera(true);
            }else {
                Set<String> newCameraCode = Arrays.stream(message.getCameraCodes().trim().split(","))
                        .map(String::trim)
                        .collect(Collectors.toSet());
                NezhaSessionManager.getInstance().switchCamera(nezhaClient, newCameraCode, false);
                nezhaClient.setCameras(newCameraCode);
                nezhaClient.setAllCamera(false);
            }
            log.info("Pc Switch Camera: success [sid: {}, uid: {}, camera: {}]", nezhaClient.getSessionId(), nezhaClient.getUserId(),  message.getCameraCodes());
        });

    }
}
